import { ApiCall } from "tsrpc";
import { masterServer } from "../../MasterServerMain";
import { ISubWorldBrief, ReqListSubWorlds, ResListSubWorlds } from "../../shared/protocols/masterServer/PtlListSubWorlds";

let subWorldsCache: ISubWorldBrief[];
let lastUpdateTime = 0;

export async function ApiListSubWorlds(call: ApiCall<ReqListSubWorlds, ResListSubWorlds>) {
    //
    if (Date.now() - lastUpdateTime > 1000) {
        let subWorlds = masterServer.worldServers.reduce((prev, next) => {
            if (next.state) {
                prev = prev.concat(next.state.subWorlds.filter(v => v.configId == call.req.type).map(v => ({
                    subWorldId: v.id,
                    displayId:v.displayId,
                    configId: v.configId,
                    name: v.name,
                    userNum: v.userNum,
                    maxUserNum: v.maxUserNum,
                    playerNum:v.playerNum,
                    maxPlayerNum:v.maxPlayerNum,
                    updateTime: v.updateTime,
                    numOfWatchers: 0,
                })))
            }
            return prev;
        }, [] as (ResListSubWorlds['subWorlds'][0] & { updateTime: number })[]);
        subWorldsCache = subWorlds.orderByDesc(v => v.updateTime).filter(v => v.userNum > 0).slice(0, 100);
    }

    call.succ({
        subWorlds: subWorldsCache
    });
}